package uf.tax.laws.spider;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Http数据访问类
 * 
 * @author sunny
 *
 */

public class HttpDAO {
	private OkHttpClient client;
	private String encoding;
	private final List<Cookie> cookieStore = new ArrayList<Cookie>();
	private final Set<String> cookiesKeys = new HashSet<String>();

	public HttpDAO() {
		encoding = "UTF-8";
		client = new OkHttpClient.Builder().cookieJar(new CookieJar() {

			@Override
			public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
				for (Cookie c : cookies) {
					String cKey = c.toString();
					if (!cookiesKeys.contains(cKey)) {
						cookieStore.add(c);
						cookiesKeys.add(cKey);
					}
				}
			}

			@Override
			public List<Cookie> loadForRequest(HttpUrl url) {
				return cookieStore;
			}
		}).connectTimeout(20, TimeUnit.SECONDS).build();
	}

	public String getEncoding() {
		return encoding;
	}

	public void setEncoding(String encoding) {
		this.encoding = encoding;
	}

	public String get(String url) {
		Request request = new Request.Builder().url(url).addHeader("Content-Encoding", encoding).build();
		Response response;
		String result = "";
		try {
			response = client.newCall(request).execute();
			result = new String(response.body().bytes(), encoding);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

	MediaType FORMENCODE = MediaType.parse("application/x-www-form-‌ urlencoded; charset=utf-8");

	public String post(String url, String params) {
		RequestBody body = RequestBody.create(FORMENCODE, params);
		Request request = new Request.Builder().url(url).addHeader("Content-Encoding", encoding).post(body).build();
		Response response;
		String result = "";
		try {
			response = client.newCall(request).execute();
			result = new String(response.body().bytes(), encoding);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}
}
